package com.zbkj.crmeb.task.plat.poizon;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.crmeb.core.config.RestTemplateConfig;
import com.factory.TaskParamsDto;
import com.utils.DateUtil;
import com.utils.PriceUtil;
import com.utils.monitor.DingMsgEnum;
import com.utils.monitor.DingTalkMsgUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.handler.orderproduct.OrderProductContext;
import com.zbkj.crmeb.handler.orderproduct.OrderProductInterface;
import com.zbkj.crmeb.plat.by.dto.Result;
import com.zbkj.crmeb.plat.enums.MerPlatEnums;
import com.zbkj.crmeb.store.dao.StoreOrderDao;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreOrderInfo;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.model.StoreProductAttrValue;
import com.zbkj.crmeb.store.response.StoreCartResponse;
import com.zbkj.crmeb.store.response.StoreProductCartProductInfoResponse;
import com.zbkj.crmeb.store.service.*;
import com.zbkj.crmeb.task.plat.AbstractPlatOperate;
import com.zbkj.crmeb.task.plat.poizon.dto.PoizonResponseBodyDto;
import com.zbkj.crmeb.task.plat.poizon.dto.PoizonRetrieveOrdersDto;
import com.zbkj.crmeb.task.plat.poizon.enums.OrderStatusEnum;
import com.zbkj.crmeb.tools.service.MoneyExchangeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 得物订单捞取
 *
 * @author: wsl
 * @date: 2024/1/29 0029 22:08
 * @ClassName: BieYangOrderTask
 */
@Component("poizonOrderTask")
@Configuration
@Slf4j
public class PoizonOrderTask extends AbstractPlatOperate<TaskParamsDto> implements ApplicationRunner {
    private static final Logger logger = LoggerFactory.getLogger(PoizonOrderTask.class);
    @Autowired
    RestTemplateConfig restTemplateConfig;
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private RelationService relationService;
    @Autowired
    private StoreProductAttrService storeProductAttrService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Resource
    private StoreOrderDao storeOrderDao;
    @Resource
    private StoreBrandService storeBrandService;
    @Resource
    private ICategoryMatchService categoryMatchService;
    @Resource
    private PriceUtil priceUtil;
    @Resource
    private MoneyExchangeService moneyExchangeService;
    @Qualifier("poizonOrderProductHandler")
    @Autowired
    private OrderProductInterface orderProductInterface;
    @Autowired
    private PoizonApi poizonApi;


//    @XxlJob("uploadProduct")
//    public void uploadProduct() {
//        OrderProductContext orderProductContext = new OrderProductContext();
//        orderProductContext.setProductId(XxlJobHelper.getJobParam());
//        Result execute = orderProductInterface.execute(orderProductContext);
//        DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT, JSON.toJSONString(execute));
//    }

    @XxlJob("fetchOrderOfPoizon")
    public void fetch() {
        String logID = UUID.randomUUID().toString();
        logger.info("logID:[{}]", logID);
        logger.info("[{}] fetchOrderOfBieYang 入口", logID);
        Date date = new Date();
        Long end = date.getTime();
        // 20天
        Long before = end - (24 * 60 * 60 * 1000 * 20);
        List<PoizonResponseBodyDto.RetrieveOrdersDataDTO.ContentDTO> orderList = new ArrayList<>();
        List<Integer> ids = new ArrayList<>();
        PoizonRetrieveOrdersDto dto = new PoizonRetrieveOrdersDto();
        dto.setStartTime(before);
        dto.setPageSize(100);
        try {
            int pageNum = 1;
            boolean flag = true;
            // 爬取得物订单数据
            while (flag) {
                dto.setPageNum(pageNum);
//                logger.info("[{}] 爬取得物订单数据请求：{}", logID, JSON.toJSONString(dto));
                PoizonResponseBodyDto<PoizonResponseBodyDto.RetrieveOrdersDataDTO> responseBodyDto = poizonApi.orderInterface(dto);
//                logger.info("[{}] 爬取得物订单数据响应：{}", logID, JSON.toJSONString(responseBodyDto));
                if (null == responseBodyDto || null == responseBodyDto.getData()) {
                    return;
                }
                if (CollectionUtils.isEmpty(responseBodyDto.getData().getContents())) {
                    flag = false;
                    break;
                }
                orderList.addAll(responseBodyDto.getData().getContents());
                pageNum++;
            }

            // 校验别得物订单状态
            validatePoizonOrderStatus(orderList);
//            logger.info("[{}] 校验得物订单状态后：{}", logID, JSON.toJSONString(orderList));
            if (CollectionUtils.isEmpty(orderList)) {
                return;
            }
            // 校验订单是否存在
            validateOrderExist(orderList);
//            logger.info("[{}] 校验订单是否存在后：{}", logID, JSON.toJSONString(orderList));
            if (CollectionUtils.isEmpty(orderList)) {
                return;
            }
            // 组装订单数据
            for (PoizonResponseBodyDto.RetrieveOrdersDataDTO.ContentDTO contentDTO : orderList) {
                StoreOrder storeOrder = assembledStoreOrder(contentDTO);
//                logger.info("[{}] 组装订单数据后：{}", logID, JSON.toJSONString(storeOrder));
                if (null == storeOrder) {
                    return;
                }
                // 新增订单
                boolean b = storeOrderService.saveOrUpdate(storeOrder);
                if (!b) {
                    log.error("新增订单异常,{}", JSON.toJSONString(storeOrder));
                    continue;
                }
                StoreOrder queryStoreOrder = storeOrderService.getOne(Wrappers.<StoreOrder>lambdaQuery().eq(StoreOrder::getOrderId, storeOrder.getOrderId()).last("limit 1"));
//                logger.info("[{}] 查询保存订单：{}", logID, JSON.toJSONString(queryStoreOrder));
                if (null == queryStoreOrder) {
                    log.error("查询保存订单异常,{}", JSON.toJSONString(storeOrder));
                    continue;
                }
                try {
                    List<StoreOrderInfo> storeOrderInfos = assembledStoreOrderInfo(contentDTO, queryStoreOrder);
//                    logger.info("[{}] 组装StoreOrderInfo数据后：{}", logID, JSON.toJSONString(storeOrderInfos));
                    storeOrderInfoService.saveOrUpdateBatch(storeOrderInfos);
                    DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT, "得物创建订单：" + storeOrder.getOrderId());
                } catch (Exception e) {
                    log.error("组装商品数据异常:", e);
                    ids.add(queryStoreOrder.getId());
                    throw new RuntimeException(e);
                }
            }

        } catch (Exception e) {
            log.error("得物创建订单异常:", e);
            // 删除订单
            storeOrderService.removeByIds(ids);
            throw new RuntimeException(e);
        }

    }

    private void validatePoizonOrderStatus(List<PoizonResponseBodyDto.RetrieveOrdersDataDTO.ContentDTO> orderList) {
        // 基础判空
        orderList.removeIf(order -> !Objects.equals(order.getOrderStatus(), OrderStatusEnum.TO_BE_CONFIRMED.getKey()));
    }

    private List<StoreOrderInfo> assembledStoreOrderInfo(PoizonResponseBodyDto.RetrieveOrdersDataDTO.ContentDTO contentDTO, StoreOrder queryStoreOrder) {
        PoizonResponseBodyDto.RetrieveOrdersDataDTO.ContentDTO.ProductDetail productDetail = contentDTO.getProductDetail();

        List<StoreOrderInfo> storeOrderInfos = new ArrayList<>();
            // 查询商品唯一属性
            StoreProductAttrValue storeProductAttrValue = getProductAttrValueInfo(productDetail.getSkuId());
            if (null == storeProductAttrValue){
                throw new RuntimeException("根据商户SKU查询商品异常");
            }
            // 根据商品属性匹配商品
            StoreProduct storeProduct = storeProductService.getOne(Wrappers.<StoreProduct>lambdaQuery().eq(StoreProduct::getId, storeProductAttrValue.getProductId()));
            if (null == storeProduct){
                throw new RuntimeException("商品不存在");
            }

            StoreOrderInfo storeOrderInfo = new StoreOrderInfo();
            storeOrderInfo.setOrderId(queryStoreOrder.getId());
//            storeOrderInfo.setInfo("{}");
            storeOrderInfo.setUnique(UUID.randomUUID().toString());
            storeOrderInfo.setOrderInfoId("POIZON_"+queryStoreOrder.getOrderId());
//            storeOrderInfo.setDeliveryAddress(StringUtils.defaultString(shippingAddress.getAddress1(),shippingAddress.getAddress2()));
            storeOrderInfo.setChildOrderNumber("POIZON_"+queryStoreOrder.getOrderId());
            storeOrderInfo.setStatus(6);
            storeOrderInfo.setRefundStatus(0);
            storeOrderInfo.setIsDel(0);
//            storeOrderInfo.setPayPrice(convertDouble2BigDecimal(clearanceAmount.getNetPrice())
//                    .add(convertDouble2BigDecimal(clearanceAmount.getMerchantCustomsDuty()))
//                    .subtract(convertDouble2BigDecimal(clearanceAmount.getBeyondPromotion()))
//                    .subtract(convertDouble2BigDecimal(clearanceAmount.getMerchantPromotion())));
            // 单价+税费  * 数量
            storeOrderInfo.setPayPrice(queryStoreOrder.getPayPrice());

            // 优惠
//            if (null != merchantPromotion){
//                storeOrderInfo.setDeductionPrice(convertDouble2BigDecimal(merchantPromotion.getValue()));
//            }
            storeOrderInfo.setCreateTime(new Date());
//            storeOrderInfo.setExchangeRate(convertDouble2BigDecimal(basicInfo.getCustomsDutyRate()));
            // 税费
//            if (null != clearanceAmount){
//                storeOrderInfo.setTaxPrice(convertDouble2BigDecimal(clearanceAmount.getMerchantCustomsDuty()));
//            }
            //todo
//            basicInfo.setMerchantSkuId("CT196151825361");
            if (null == storeProductAttrValue){
                log.error("查询商品信息异常:{}",productDetail.getSkuId());
            }

            // local商品信息
            BeanUtils.copyProperties(storeProduct,storeOrderInfo);
            storeOrderInfo.setProductId(storeProduct.getId());
            storeOrderInfo.setKeyword(storeProduct.getKeyword());
            storeOrderInfo.setStoreName(storeProduct.getStoreName());
            storeOrderInfo.setCateId(storeProduct.getCateId());
            storeOrderInfo.setVipReducePrice(storeProduct.getVipPrice());
            storeOrderInfo.setNum(productDetail.getQuantity());
            storeOrderInfo.setIsWzbsc(false);
            storeOrderInfo.setId(null);

            // 供应商ID
            storeOrderInfo.setSuppliersId(storeProduct.getSuppliersId());

            // 商品购物车信息
            StoreCartResponse storeCartResponse = new StoreCartResponse();
            storeCartResponse.setProductAttrUnique(storeProductAttrValue.getSourceSkuId());
            storeCartResponse.setType("product");
            storeCartResponse.setProductId(storeProductAttrValue.getProductId());
            storeCartResponse.setCartNum(productDetail.getQuantity());
            storeCartResponse.setIsNew(true);
            StoreProductCartProductInfoResponse storeProductCartProductInfoResponse = new StoreProductCartProductInfoResponse();
            BeanUtils.copyProperties(storeProduct,storeProductCartProductInfoResponse);
            storeProductCartProductInfoResponse.setAttrInfo(storeProductAttrValue);
            storeProductCartProductInfoResponse.setImage(storeProductAttrValue.getImage());
            storeCartResponse.setProductInfo(storeProductCartProductInfoResponse);

            storeOrderInfo.setInfo(JSON.toJSONString(storeCartResponse));

            storeOrderInfo.setCreateTime(new Date());
            // 扩展字段
            storeOrderInfo.addFeature("merchantProductId",productDetail.getSpuId());
            storeOrderInfo.addFeature("productId",productDetail.getSpuId());
            storeOrderInfo.addFeature("merchantSkuId",productDetail.getSkuId());
            storeOrderInfo.addFeature("skuId",productDetail.getSkuId());

            storeOrderInfo.addFeature("merId",productDetail.getSpuId().split("_")[1]);
            storeOrderInfos.add(storeOrderInfo);

        return storeOrderInfos;
    }

    private StoreProductAttrValue getProductAttrValueInfo(String merchantSkuId) {

        if (StringUtils.isBlank(merchantSkuId)) {
            return null;
        }
        StoreProductAttrValue storeProductAttrValue = null;
        if (merchantSkuId.startsWith("SUYUN") && merchantSkuId.split("SUYUN").length > 1) {
            storeProductAttrValue = storeProductAttrValueService.getById(merchantSkuId.split("SUYUN")[1]);
        } else {
            storeProductAttrValue = storeProductAttrValueService.getOne(Wrappers.<StoreProductAttrValue>lambdaQuery().eq(StoreProductAttrValue::getSelfSourceSkuId, merchantSkuId));
        }
        return storeProductAttrValue;
    }


    private StoreOrder assembledStoreOrder(PoizonResponseBodyDto.RetrieveOrdersDataDTO.ContentDTO contentDTO) {
        PoizonResponseBodyDto.RetrieveOrdersDataDTO.ContentDTO.ProductDetail productDetail = contentDTO.getProductDetail();
        StoreOrder storeOrder = new StoreOrder();
        storeOrder.setOutOrderId(contentDTO.getChannelOrderNo());
        storeOrder.setOrderId(getOrderId(contentDTO.getChannelOrderNo()));
        storeOrder.setUid(240430);
        storeOrder.setRealName("");
        storeOrder.setUserPhone("");
        storeOrder.setAreaType(3);
        storeOrder.setUserAddress("");
//        storeOrder.setFreightPrice(convertDouble2BigDecimal(infoSummary.getTotalShippingFee()));
        storeOrder.setTotalNum(1);
        storeOrder.setTotalPrice(productDetail.getPrice());
//        storeOrder.setTotalPostage(convertDouble2BigDecimal(infoSummary.getTotalShippingFee()));
        storeOrder.setPayPrice(productDetail.getPrice());
        storeOrder.setDeductionPrice(BigDecimal.ZERO);
//        storeOrder.setCouponId(0);
//        storeOrder.setCouponPrice(convertDouble2BigDecimal(infoSummary.getPromotionAmount()));
        storeOrder.setPaid(true);
        storeOrder.setPayTime(DateUtil.longToDate(Long.parseLong(contentDTO.getModifyTime())));
        storeOrder.setPayType("Unknown");
        storeOrder.setCreateTime(new Date());
        storeOrder.setCreateName("SYS");
        // 代发货
        storeOrder.setStatus(6);
        storeOrder.setRefundStatus(0);
        storeOrder.setRefundReasonWapImg("");


        storeOrder.setDeliveryName("");
        storeOrder.setIsDel(false);

        String merId = productDetail.getSpuId().split("_")[1];
        storeOrder.setMerId(Integer.valueOf(merId));
        storeOrder.setShippingType(1);
        storeOrder.setPushStatus(0);

//        storeOrder.setProvince(shippingAddress.getState());
//        storeOrder.setCity(shippingAddress.getCity());
//        storeOrder.setDistrict(shippingAddress.getDistrict());
//        storeOrder.setDetail(shippingAddress.getAddress1());
//        storeOrder.setIdCard(clearanceInfo.getIdentityNumber());
//        storeOrder.setSource(9);
        // 支付单号
//        storeOrder.setPayNo(clearanceInfo.getPaymentOrderId());
        storeOrder.setUnique(UUID.randomUUID().toString());
//        storeOrder.setPayName(clearanceInfo.getLastName()+clearanceInfo.getFirstName());

        storeOrder.setRemark("POIZON");
        return storeOrder;
    }

    private String getOrderId(String orderId) {
        return orderId.replaceAll("[-|_]", "");
    }

    public BigDecimal convertDouble2BigDecimal(Double value) {
        return null == value ? BigDecimal.ZERO : BigDecimal.valueOf(value).setScale(2, RoundingMode.HALF_UP);

    }

    private void validateOrderExist(List<PoizonResponseBodyDto.RetrieveOrdersDataDTO.ContentDTO> orderList) {

        List<String> orderIdNos = orderList.stream().map(PoizonResponseBodyDto.RetrieveOrdersDataDTO.ContentDTO::getChannelOrderNo).collect(Collectors.toList());
        List<StoreOrder> storeOrderList = storeOrderService.list(Wrappers.<StoreOrder>lambdaQuery().in(StoreOrder::getOutOrderId, orderIdNos));
        if (CollectionUtils.isEmpty(storeOrderList)) {
            return;
        }
        Map<String, StoreOrder> map = storeOrderList.stream().collect(Collectors.toMap(StoreOrder::getOutOrderId, v -> v));
        orderList.removeIf(order -> map.containsKey(order.getChannelOrderNo()));
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
    }

    public static void main(String[] args) {
    }
}
